package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import com.project.dao.IUserDao;
import com.project.servic.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("land")
    public String Land(String name, String password, HttpServletRequest req) {
        UserBean user = service.land(name, password);
        if (user!=null){
        req.getSession().setAttribute("loginUser", user);
        return "ok";
    }
        return"no";
}
    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req){
        UserBean user = (UserBean)req.getSession().getAttribute("loginUser");
        return user;
    }
@RequestMapping("add")
public String add(@Valid UserBean em, BindingResult br) throws JsonProcessingException {
    if (br.hasErrors())//判断是否有验证失败的信息
    {//得到校验失败的集合
        List<FieldError> errors= br.getFieldErrors();
        ObjectMapper om = new ObjectMapper();
        String errorInfo = om.writeValueAsString(errors);
        return errorInfo;
    }
    service.add(em);
    return "ok";
}
}
